class Observer {
  constructor(data) {
    this.walk(data);
  }

  walk(data) {
    // 判断data是否为对象
    if (!data || typeof data !== 'object') {
      return;
    }
    // 遍历data对象
    Object.keys(data)
      .forEach(key => {
        this.defineReactive(data, key, data[key]);
      });
  }

  defineReactive(obj, key, val) {
    let that = this;
    let dep = new Dep();
    // 如果val是对象 则讲起转换为响应式数据
    this.walk(val);
    Object.defineProperty(obj, key, {
      enumerable: true,
      configurable: true,
      get() {
        Dep.target && dep.addSub(Dep.target);
        return val;
      },
      set(v) {
        if (v === val) {
          return;
        }
        val = v;
        that.walk(v);
        dep.notify()
      }
    });
  }
}
